<template>
      <XtxBread>
        <XtxBreadItem to="/">首页</XtxBreadItem>
        <XtxBreadItem v-if="cateInfo.fcate" :to='`/category/${cateInfo.fcate.id}`'>{{cateInfo.fcate.name}}</XtxBreadItem>
        <Transition name="fade-right" mode="out-in">
          <XtxBreadItem :key="cateInfo.scate.id" v-if="cateInfo.scate">{{cateInfo.scate.name}}</XtxBreadItem>
        </Transition>
      </XtxBread>
</template>
<script>
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { computed } from 'vue'
export default {
  name: 'SubBread',
  setup () {
    const store = useStore()
    const route = useRoute()

    const cateInfo = computed(() => {
      // 定义最终计算结果
      const info = {
        fcate: null,
        scate: null
      }

      // 循环所有一级分类,性能优化用some找到匹配数据,终止循环,替代forEach
      store.getters.cates.some(firstCate => {
        // 找出相对应的二级分类
        const secondCate = firstCate.children && firstCate.children.find(item => {
          return item.id === route.params.id
        })

        // 找到之后赋值
        if (secondCate) {
          // 一级分类
          info.fcate = {
            id: firstCate.id,
            name: firstCate.name
          }

          // 二级分类
          info.scate = {
            id: secondCate.id,
            name: secondCate.name
          }
          // some方法,返回true,终止循环
          return true
        }
      })

      // 返回计算结果
      return info
    })

    return { cateInfo }
  }

}
</script>
